<?php
namespace frontend\models;

use common\models\User;
use yii\base\Model;
use Yii;

/**
 * Signup form
 */
class SignupForm extends Model
{
    public $login_account;
    public $email;
    public $password;

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            ['login_account', 'filter', 'filter' => 'trim'],
            ['login_account', 'required'],
            ['login_account', 'unique', 'targetClass' => '\common\models\User', 'message' => '此用户名已被占用.'],
            ['login_account', 'string', 'min' => 2, 'max' => 255],

            ['email', 'filter', 'filter' => 'trim'],
            ['email', 'required'],
            ['email', 'email'],
            ['email', 'unique', 'targetClass' => '\common\models\User', 'message' => '此邮箱已被占用.'],

            ['password', 'required'],
            ['password', 'string', 'min' => 6],
        ];
    }

    /**
     * Signs user up.
     *
     * @return User|null the saved model or null if saving fails
     */
    public function signup()
    {
        if ($this->validate()) {
            $user = new User();
//             $user->login_account = $this->login_account;
//             $user->email = $this->email;
//             $user->setPassword($this->password);
//             $user->generateAuthKey();
//             if ($user->save()) {
//                 return $user;
//             }
            $pwd = $user->setPassword($this->password);
            $sql = "insert into {{%sys_user}} (login_account,password,email) values(:login_account,:password,:email)";
            $db = \Yii::$app->db->createCommand($sql);
            $db->bindParam(':login_account', $this->login_account);
            $db->bindParam(':password', $pwd);
            $db->bindParam(':email', $this->email);
            if ($db->execute()) {
                return $user;
            }
            
        }

        return null;
    }
}
